import { enableFirebaseOnH5Only, firebaseConfig } from './config.js'

let firebaseApp = null
let firebaseAuth = null
let firebaseFirestore = null
let firebaseAnalytics = null

function shouldInit() {
    // #ifdef H5
    if (enableFirebaseOnH5Only) return true
    // #endif
    // #ifndef H5
    if (!enableFirebaseOnH5Only) return true
    // #endif
    return false
}

export async function initFirebase() {
    if (firebaseApp || !shouldInit()) return { firebaseApp, firebaseAuth, firebaseFirestore, firebaseAnalytics }

    const { initializeApp } = await import('firebase/app')

    firebaseApp = initializeApp(firebaseConfig)

    // Lazy import services to reduce bundle size
    try {
        const { getAuth } = await import('firebase/auth')
        firebaseAuth = getAuth(firebaseApp)
    } catch (e) {}

    try {
        const { getFirestore } = await import('firebase/firestore')
        firebaseFirestore = getFirestore(firebaseApp)
    } catch (e) {}

    // Analytics only works on web
    // #ifdef H5
    try {
        const { getAnalytics, isSupported } = await import('firebase/analytics')
        if (await isSupported()) {
            firebaseAnalytics = getAnalytics(firebaseApp)
        }
    } catch (e) {}
    // #endif

    return { firebaseApp, firebaseAuth, firebaseFirestore, firebaseAnalytics }
}

export function getFirebase() {
    return { firebaseApp, firebaseAuth, firebaseFirestore, firebaseAnalytics }
}


